
import { _decorator, Component, Node } from 'cc';
import { TileMapManager } from '../Tile/TileMapManager';
import { createUINode } from '../../Utils/idnex';
import levels, { ILevel } from '../../levels';
import { DataManager } from '../../Runtime/DataManager';
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager';
import EventManager from '../../Runtime/EventManager';
import { EVENT_ENUM } from '../../Enum';
import { PlayerManager } from '../Player/PlayerManager';

const { ccclass, property } = _decorator;

@ccclass('BattleManager')
export class BattleManager extends Component {
    level: ILevel
    stage: Node;

    onLoad() {
        //绑定事件
        EventManager.Instance.on(EVENT_ENUM.NEXT_LEVEL, this.nextLevel, this)
    }

    onDestory() {
        //事件解绑
        EventManager.Instance.Off(EVENT_ENUM.NEXT_LEVEL, this.nextLevel);
    }

    start() {
        this.generateStage()
        this.initLevel()
    }

    async initLevel() {
        const level = levels[`level${DataManager.Instance.levelIndex}`];
        if (level) {
            //除了全部重置,这个是为了刷新地图到第二关
            this.clearLevel();
            this.level = level;

            DataManager.Instance.mapInfo = this.level.mapInfo;
            DataManager.Instance.mapRowCount = this.level.mapInfo.length || 0;
            DataManager.Instance.mapColumnCount = this.level.mapInfo[0].length || 0;

            this.generateTileMap();
            await this.generatePlayer();
        }
    }

    generatePlayer() {
        const node = createUINode();
        node.setParent(this.stage);
        const playerManager = node.addComponent(PlayerManager);
        playerManager.init();
    }

    nextLevel() {
        DataManager.Instance.levelIndex++;
        this.initLevel();
    }

    clearLevel() {
        //删除节点的所有子节点并且重置记录的部分信息
        this.stage.destroyAllChildren();
        DataManager.Instance.reset();
    }


    generateStage() {
        this.stage = createUINode();
        this.stage.setParent(this.node);
    }

    async generateTileMap() {
        const tileMap = createUINode();
        tileMap.setParent(this.stage);
        const tileMapmanager = tileMap.addComponent(TileMapManager);
        await tileMapmanager.init();

        this.adaptPos()
    }

    adaptPos() {
        console.log("我被执行了-1")
        const { mapRowCount, mapColumnCount } = DataManager.Instance;
        const disX = (TILE_WIDTH * mapRowCount) / 2
        const disY = (TILE_HEIGHT * mapColumnCount) / 2 + 80
        //这个的Position控制的是地图和人物一起的
        this.stage.setPosition(-disX, disY);
    }

}


